package com.pfzy.ui.activity.pick;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.pfzy.ui.R;
import com.pfzy.ui.activity.pick.adapter.ArrayWheelAdapter;
import com.pfzy.ui.activity.pick.listener.OnOptionsSelectChangeListener;
import com.pfzy.ui.log.MyLog;
import com.pfzy.ui.utils.PickerViewAnimateUtil;
import com.pfzy.ui.view.wheelview.WheelView;
import com.pfzy.ui.view.wheelview.listener.OnItemSelectedListener;

import java.util.List;

public class PickerDlg4<T> extends Dialog implements View.OnClickListener {
    private ViewGroup dialogView;// 附加Dialog 的 根View
    private ViewGroup contentContainer;
    private Dialog mDialog;
    private Animation outAnim;
    private Animation inAnim;
    private int animGravity = Gravity.BOTTOM;
    private boolean isRestoreItem; //切换时，还原第一项
    private WheelView wv_option1;
    private WheelView wv_option2;
    private int textSize = 18;
    public Typeface font = Typeface.MONOSPACE;//字体样式
    private float lineSpacingMultiplier = 1.6f; // 条目间距倍数 默认1.6
    private int textColorOut = 0xFFa8a8a8; // 分割线以外的文字颜色
    private int textColorCenter = 0xFF2a2a2a; // 分割线之间的文字颜色
    public int x_offset_one = 0, x_offset_two = 0;//x轴偏移量
    public boolean cyclic1 = false, cyclic2 = false;// 是否循环，默认否
    private boolean isCenterLabel = false;// 是否只显示中间的label,默认每个item都显示
    private List<T> mOptions1Items;
    private List<List<T>> mOptions2Items;
    private OnItemSelectedListener wheelListener_option1;
    private OnItemSelectedListener wheelListener_option2;
    private boolean linkage = true;//默认联动
    public int option1, option2;//默认选中项
    public OnOptionsSelectChangeListener optionsSelectChangeListener;// 选项上选择已更改

    public PickerDlg4(@NonNull Context context) {
        super(context);
        initWindow();
        initAnim();
        initView();
    }

    private void initWindow() {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        // 如果是对话框模式
        dialogView = (ViewGroup) layoutInflater.inflate(R.layout.layout_basepickerview, null, false);
        // 设置界面的背景为透明
        dialogView.setBackgroundColor(Color.TRANSPARENT);
        // 这个是真正要加载选择器的父布局
        contentContainer = dialogView.findViewById(R.id.content_container);
        // 设置对话框 默认左右间距屏幕30
        params.leftMargin = 30;
        params.rightMargin = 30;
        contentContainer.setLayoutParams(params);

        // 创建对话框
        createDialog();
        //给背景设置点击事件,这样当点击内容以外的地方会关闭界面
        dialogView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    protected void initAnim() {
        inAnim = getInAnimation();
        outAnim = getOutAnimation();
    }

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.dlg_picker_4, contentContainer);
        // 确定和取消按钮
        Button btnSubmit = contentContainer.findViewById(R.id.dlg_picker_4_btn);
        ImageView btnCancel = contentContainer.findViewById(R.id.dlg_picker_4_close);
        btnSubmit.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        wv_option1 = contentContainer.findViewById(R.id.dlg_picker_4_1);
        wv_option2 = contentContainer.findViewById(R.id.dlg_picker_4_2);

        wv_option1.setTextSize(textSize);
        wv_option2.setTextSize(textSize);

        wv_option1.setLabel("省");
        wv_option2.setLabel("市");

        wv_option1.setTextXOffset(x_offset_one);
        wv_option2.setTextXOffset(x_offset_two);

        wv_option1.setCyclic(cyclic1);
        wv_option2.setCyclic(cyclic2);

        wv_option1.setDividerType(WheelView.DividerType.FILL);
        wv_option2.setDividerType(WheelView.DividerType.FILL);

        wv_option1.setTypeface(font);
        wv_option2.setTypeface(font);

        // 设置分割线的颜色
        wv_option1.setDividerColor(Color.YELLOW);
        wv_option2.setDividerColor(Color.YELLOW);

        wv_option1.setLineSpacingMultiplier(lineSpacingMultiplier);
        wv_option2.setLineSpacingMultiplier(lineSpacingMultiplier);

        wv_option1.setTextColorOut(textColorOut);
        wv_option2.setTextColorOut(textColorOut);

        wv_option1.setTextColorCenter(textColorCenter);
        wv_option2.setTextColorCenter(textColorCenter);

        wv_option1.isCenterLabel(isCenterLabel);
        wv_option2.isCenterLabel(isCenterLabel);
    }

    public void createDialog() {
        if (dialogView != null) {
            mDialog = new Dialog(getContext(), R.style.custom_dialog2);
            mDialog.setCancelable(false);
            mDialog.setContentView(dialogView);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(R.style.pickerview_dialogAnim);
                dialogWindow.setGravity(Gravity.CENTER);
            }
        }
    }

    public Animation getInAnimation() {
        int res = PickerViewAnimateUtil.getAnimationResource(this.animGravity, true);
        return AnimationUtils.loadAnimation(getContext(), res);
    }

    public Animation getOutAnimation() {
        int res = PickerViewAnimateUtil.getAnimationResource(this.animGravity, false);
        return AnimationUtils.loadAnimation(getContext(), res);
    }

    public void setSelectOptions(int option1, int option2) {
        this.option1 = option1;
        this.option2 = option2;
    }

    public void setPicker(List<T> options1Items, List<List<T>> options2Items) {
        this.mOptions1Items = options1Items;
        this.mOptions2Items = options2Items;

        // 选项1
        wv_option1.setAdapter(new ArrayWheelAdapter(mOptions1Items));// 设置显示数据
        wv_option1.setCurrentItem(0);// 初始化时显示的数据

        // 选项2
        if (mOptions2Items != null) {
            wv_option2.setAdapter(new ArrayWheelAdapter(mOptions2Items.get(0)));// 设置显示数据
        }
        wv_option2.setCurrentItem(wv_option2.getCurrentItem());// 初始化时显示的数据

        wv_option1.setIsOptions(true);
        wv_option2.setIsOptions(true);

        if (this.mOptions2Items == null) {
            wv_option2.setVisibility(View.GONE);
        } else {
            wv_option2.setVisibility(View.VISIBLE);
        }

        // 联动监听器
        wheelListener_option1 = new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                int opt2Select = 0;
                if (mOptions2Items == null) {//只有1级联动数据
                } else {
                    if (!isRestoreItem) {
                        opt2Select = wv_option2.getCurrentItem();//上一个opt2的选中位置
                        //新opt2的位置，判断如果旧位置没有超过数据范围，则沿用旧位置，否则选中最后一项
                        opt2Select = opt2Select >= mOptions2Items.get(index).size() - 1 ? mOptions2Items.get(index).size() - 1 : opt2Select;
                    }
                    wv_option2.setAdapter(new ArrayWheelAdapter(mOptions2Items.get(index)));
                    wv_option2.setCurrentItem(opt2Select);
                }
            }
        };

        wheelListener_option2 = new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
            }
        };

        // 添加联动监听
        if (options1Items != null && linkage) {
            wv_option1.setOnItemSelectedListener(wheelListener_option1);
        }
        if (options2Items != null && linkage) {
            wv_option2.setOnItemSelectedListener(wheelListener_option2);
        }

        reSetCurrentItems();
    }

    private void reSetCurrentItems() {
        setCurrentItems(option1, option2);
    }

    public void setCurrentItems(int option1, int option2) {
        if (linkage) {
            itemSelected(option1, option2);
        } else {
            wv_option1.setCurrentItem(option1);
            wv_option2.setCurrentItem(option2);
        }
    }

    private void itemSelected(int opt1Select, int opt2Select) {
        if (mOptions1Items != null) {
            wv_option1.setCurrentItem(opt1Select);
        }
        if (mOptions2Items != null) {
            wv_option2.setAdapter(new ArrayWheelAdapter(mOptions2Items.get(opt1Select)));
            wv_option2.setCurrentItem(opt2Select);
        }
    }

    /**
     * 返回当前选中的结果对应的位置数组 因为支持三级联动效果，分三个级别索引，0，1，2。
     * 在快速滑动未停止时，点击确定按钮，会进行判断，如果匹配数据越界，则设为0，防止index出错导致崩溃。
     *
     * @return 索引数组
     */
    public int[] getCurrentItems() {
        int[] currentItems = new int[3];
        currentItems[0] = wv_option1.getCurrentItem();

        if (mOptions2Items != null && mOptions2Items.size() > 0) {//非空判断
            currentItems[1] = wv_option2.getCurrentItem() > (mOptions2Items.get(currentItems[0]).size() - 1) ? 0 : wv_option2.getCurrentItem();
        } else {
            currentItems[1] = wv_option2.getCurrentItem();
        }

        return currentItems;
    }

    public void showDialog() {
        if (mDialog != null) {
            mDialog.show();
        }
    }

    public void dismissDialog() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dlg_picker_4_close:
                dismissDialog();
                break;
            case R.id.dlg_picker_4_btn:
                int[] optionsCurrentItems = getCurrentItems();
                if (optionsSelectChangeListener != null) {
                    optionsSelectChangeListener.onOptionsSelectChanged(optionsCurrentItems[0], optionsCurrentItems[1], 0);
                }
                dismissDialog();
                break;
            default:
                break;
        }
    }

    /**
     * @param listener 切换item项滚动停止时，实时回调监听。
     * @return
     */
    public void setOptionsSelectChangeListener(OnOptionsSelectChangeListener listener) {
        optionsSelectChangeListener = listener;
    }

    private void _logd(String msg) {
        MyLog.logd("时钟选择器4 : " + msg);
    }
}
